#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include <unistd.h>
#include "gaia_common.h"

int gaia_callback(const char *post_data);

/*
//just test
int main(void)
{
  int result = 0; 
  char *url = "www.shopex.cn";
  result = gaia_callback(url);
  
  if(0 != result)
  {
    fprintf(stderr,"callback fail!\n");
    return 1;
  } 
  fprintf(stderr,"callback success!\n");

  return 0;
}
*/

/****************************************************
 * 函数功能：调用web端callback地址，将操作结果返回到web端  
 * 返回值：成功 0，失败 1
 * 参数：url返回
 ****************************************************/
int gaia_callback(const char *post_data)
{
  //printf("use callback!\n");
  //printf("post data = %s\n",post_data);
  CURL *curl;
  CURLcode res;

  /* 写body文件,将默认的显示重定向到文件里去 */
  FILE *bodyfd;
  char *bodyfile = "/tmp/.bodyfile.txt";

  /* 初始化curl handle */
  curl = curl_easy_init();
  
  /* 检查curl handle初始化*/
  if(!curl)
  {
    fprintf(stderr,"init curl fail!\n");
    return 1;
  }
  
  /* 打开文件句柄成功后，将输出信息重定向到文件里去 */
  if( (bodyfd = fopen(bodyfile,"w")) != NULL)
    curl_easy_setopt(curl,CURLOPT_WRITEDATA,bodyfd);
  /* 设置如何处理url*/
  curl_easy_setopt(curl,CURLOPT_URL,CALLBACK_URL);
  /* post选项 */
  curl_easy_setopt(curl,CURLOPT_POSTFIELDS,post_data);
  /* 设置超时时间 */
  curl_easy_setopt(curl,CURLOPT_TIMEOUT,3);
  /* 执行操作 */
  res = curl_easy_perform(curl);

  if(CURLE_OK != res )
  {
    fprintf(stderr,"curl_easy_perform fail!\n");
    return 1;
  }

  /* 关闭curl handle */
  curl_easy_cleanup(curl);

  return 0;
}
